package com.skivingcloud.admin.sys.controller;


import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.skivingcloud.admin.annotation.ModifyAnnotaionFactory;
import com.skivingcloud.admin.annotation.UserOperateLog;
import com.skivingcloud.admin.sys.entity.SysRole;
import com.skivingcloud.admin.sys.entity.SysRoleMenu;
import com.skivingcloud.admin.sys.entity.SysUserRole;
import com.skivingcloud.admin.sys.entity.User;
import com.skivingcloud.admin.sys.service.ISysMenuService;
import com.skivingcloud.admin.sys.service.ISysRoleService;
import com.skivingcloud.admin.sys.service.ITenantService;
import com.skivingcloud.admin.utils.UserUtil;
import com.skivingcloud.common.contants.Constant;
import com.skivingcloud.common.exception.BusinessException;
import com.skivingcloud.common.utils.PageUtils;
import com.skivingcloud.common.utils.R;
import com.skivingcloud.common.utils.StringUtils;
import com.skivingcloud.common.utils.TreeUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * 角色 前端控制器
 * </p>
 *
 * @author skivingcloud
 * @since 2022-01-29
 */
@RestController
@RequestMapping("/sys/role")
public class SysRoleController {

	private static Logger log = LoggerFactory.getLogger(SysRoleController.class);

	@Autowired
	private ISysRoleService sysRoleService;
	@Autowired
	private ISysMenuService sysMenuService;
	@Autowired
	private ITenantService tenantService;

	/**
	 * 角色分页查询
	 * 
	 * @param params
	 * @return
	 */
	@PostMapping("/list")
	// @RequiresPermissions("sys:role:list")
	public R list(@RequestBody Map<String, Object> params) {
		// 如果不是超级管理员，则只查询自己租户的角色列表
		User user = UserUtil.getUser();
		PageUtils page = sysRoleService.queryPage(params, user);

		return R.ok().put("page", page);
	}

	/**
	 * 根据角色id加载资源树权限
	 * 
	 * @param id 角色id
	 * @return
	 * @throws Exception
	 */
	@GetMapping("/getRoleResTree/{id}")
	public R getRoleResTree(@PathVariable("id") String id) throws Exception {
		List<String> terminals = new ArrayList<String>();
		User user = UserUtil.getUser();
		List<TreeUtils> list = sysMenuService.gerResTreeByTerminal(terminals, user);
		List<SysRoleMenu> asingRes = new ArrayList<SysRoleMenu>();
		asingRes = sysRoleService.getResTreeByRoleId(id);
		return R.ok().put("tree", list).put("asingRes", asingRes);
	}

	/**
	 * 根据id查询角色信息
	 * 
	 * @param roleId
	 * @return
	 */
	@GetMapping("/info/{roleId}")
	// @RequiresPermissions("sys:role:info")
	public R info(@PathVariable("roleId") String roleId) {
		SysRole role = sysRoleService.selectById(roleId);
		return R.ok().put("role", role);
	}

	/**
	 * 新增角色信息
	 * 
	 * @param role
	 * @return
	 */
	@PostMapping("/save")
	// @RequiresPermissions("sys:role:save")
	@UserOperateLog(module = "系统功能", methods = "save", description = "新增角色", functionNo = "101044")
	public R save(@RequestBody SysRole role) {
		try {
			User user = UserUtil.getUser();
			sysRoleService.save(role, user);
			ModifyAnnotaionFactory.newInstance().ModifyAnnotation(getClass(), UserOperateLog.class, "save", "bussid",
					role.getId(), role.getClass());
			return R.ok();
		} catch (Exception e) {
			log.error("保存角色信息失败", e);
			return R.error("保存角色信息失败");
		}
	}

	/**
	 * 修改角色信息
	 * 
	 * @param role
	 * @return
	 */
	@PostMapping("/update")
	@UserOperateLog(module = "系统功能", methods = "update", description = "修改角色", functionNo = "101045")
	// @RequiresPermissions("sys:role:update")
	public R update(@RequestBody SysRole role) {

		try {
			User user = UserUtil.getUser();
			sysRoleService.update(role, user);
			ModifyAnnotaionFactory.newInstance().ModifyAnnotation(getClass(), UserOperateLog.class, "update", "bussid",
					role.getId(), role.getClass());
			return R.ok();
		} catch (Exception e) {
			log.error("保存角色信息失败", e);
			return R.error("保存角色信息失败");
		}
	}

	/**
	 * 删除角色信息
	 * 
	 * @param roleIds
	 * @return
	 */
	@PostMapping("/delete")
	// @RequiresPermissions("sys:role:delete")
	@UserOperateLog(module = "系统功能", methods = "delete", description = "删除角色", functionNo = "101046")
	public R delete(@RequestBody String[] roleIds) {
		try {
			for (String roleId : roleIds) {
				if ("1".equals(roleId)) {
					return R.error("内置角色请勿删除！");
				}
			}
			sysRoleService.deleteBatch(roleIds);
			ModifyAnnotaionFactory.newInstance().ModifyAnnotation(getClass(), UserOperateLog.class, "delete", "bussid",
					roleIds.toString(), roleIds.getClass());
			return R.ok();
		} catch (Exception e) {
			log.error("删除角色信息失败", e);
			return R.error("删除角色信息失败");
		}
	}

	/**
	 * 设置角色资源
	 * 
	 * @param role
	 * @return
	 */
	@PostMapping("/setRoleMenu")
	@UserOperateLog(module = "系统功能", methods = "setRoleMenu", description = "设置资源权限", functionNo = "101047")
	public R setRoleMenu(@RequestBody SysRole role) {
		try {
			User user = UserUtil.getUser();
			sysRoleService.setRoleMenu(role, user);
			ModifyAnnotaionFactory.newInstance().ModifyAnnotation(getClass(), UserOperateLog.class, "setRoleMenu",
					"bussid", role.getId().toString(), role.getClass());
			return R.ok();
		} catch (Exception e) {
			log.error("设置资源权限失败", e);
			return R.error("设置资源权限失败");
		}
	}

	/**
	 * 获取角色下用户列表
	 * 
	 * @param params
	 * @return
	 */
	@GetMapping("/roleUserList")
	public R roleUserList(@RequestParam Map<String, Object> params) {
		PageUtils page = sysRoleService.queryUserRoleList(params);
		return R.ok().put("page", page);
	}

	/**
	 * 获取有效用户，不包含已添加的用户，只能选择当前角色租户下的用户
	 * 
	 * @param params
	 * @return
	 */
	@PostMapping("/roleUserNoChooseList")
	public R roleUserNoChooseList(@RequestBody Map<String, Object> params) {
		User user = UserUtil.getUser();
		PageUtils page = sysRoleService.queryUserRoleNoChooseList(params, user);
		return R.ok().put("page", page);
	}

	/**
	 * 给角色添加用户
	 * 
	 * @param params
	 * @return
	 */
	@PostMapping("/setSysRoleUser")
	@UserOperateLog(module = "系统功能", methods = "setSysRoleUser", description = "设置用户角色", functionNo = "101048")
	public R setSysRoleUser(@RequestBody Map<String, Object> params) {
		try {
			String userId = params.get("userId") == null ? null : params.get("userId").toString();
			if (StringUtils.isBlank(userId)) {
				throw new BusinessException("用户id不能为空！");
			}
			String roleId = params.get("roleId") == null ? null : params.get("roleId").toString();
			if (StringUtils.isBlank(roleId)) {
				throw new BusinessException("角色id不能为空！");
			}
			User user = UserUtil.getUser();
			sysRoleService.setSysRoleUser(userId, roleId, user);
			ModifyAnnotaionFactory.newInstance().ModifyAnnotation(getClass(), UserOperateLog.class, "setSysRoleUser",
					"bussid", params.toString(), Map.class);
			return R.ok();
		} catch (BusinessException e) {
			log.error("设置用户角色失败" + ":" + e.getMessage(), e);
			return R.error(e.getMessage());
		} catch (Exception e) {
			log.error("设置用户角色失败", e);
			return R.error("设置用户角色失败");
		}
	}

	/**
	 * 根据租户和角色id加载资源树权限
	 * 
	 * @param tenantId
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@GetMapping("/resetTenantRoleResTree/{tenantId}/{id}")
	public R resetTenantRoleResTree(@PathVariable("tenantId") String tenantId, @PathVariable("id") String id)
			throws Exception {
		User user = UserUtil.getUser();
		if (!user.getTenantId().equals(Constant.SUPER_ADMIN_TENANTID)) {
			tenantId = user.getTenantId();
		}
		List<TreeUtils> list = tenantService.getTenantRoleResTree(tenantId);
		List<SysRoleMenu> asingRes = new ArrayList<SysRoleMenu>();
		asingRes = sysRoleService.getResTreeByRoleId(id);
		return R.ok().put("tree", list).put("asingRes", asingRes);
	}
	
	/**
	 * 根据租户和角色id加载资源树权限
	 * 
	 * @param tenantId
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@PostMapping("/deleteSysRoleUser")
	public R deleteSysRoleUser(@RequestBody SysUserRole sysUserRole) throws Exception {
		try {
			User user = UserUtil.getUser();
			sysRoleService.deleteSysRoleUser(sysUserRole.getId(), user);
			return R.ok();
		} catch (BusinessException e) {
			log.error("删除角色下用户失败" + ":" + e.getMessage(), e);
			return R.error("e.getMessage()");
		} catch (Exception e) {
			log.error("删除角色下用户失败", e);
			return R.error("删除角色下用户失败");
		}
	}
}
